<template>
  <div class="container">
    <el-dialog
      title="新增学科"
      :visible.sync="addDialog"
      width="30%"
      :before-close="handleClose"
    >
      <span>
        <el-form :model="subjectFrom" ref="subjectFrom" :rules="rules">
          <el-form-item label="学科名称" prop="subjectName">
            <el-input
              v-model="subjectFrom.subjectName"
              autocomplete="off"
              style="width: 80%"
              placeholder="请输入学科名称"
            ></el-input>
          </el-form-item>
          <el-form-item label="是否显示" prop="isFrontDisplay">
            <el-switch
              :active-value="1"
              :inactive-value="0"
              v-model="subjectFrom.isFrontDisplay"
            >
            </el-switch>
          </el-form-item>
        </el-form>
      </span>
      <span slot="footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="confirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { add } from '@/api/hmmm/subjects.js'
export default {
  props: {
    addDialog: {
      type: Boolean
    },
    loadList: {
      type: Function,
      required: true
    }
  },
  data() {
    return {
      subjectFrom: {
        isFrontDisplay: 1,
        subjectName: ''
      },
      rules: {
        subjectName: [
          { required: true, message: '学科名称不能为空', trigger: 'blur' },
          { min: 1, max: 12, message: '长度在 1 到 12 个字符', trigger: 'blur' }
        ],
        isFrontDisplay: [{ required: true, message: '请选择状态' }]
      }
    }
  },
  methods: {
    // 取消添加学科
    cancel() {
      this.$emit('closed')
      this.$refs.subjectFrom.resetFields()
      this.$message.info('取消添加')
    },
    // 确认添加学科
    confirm() {
      this.$refs.subjectFrom.validate(async (val) => {
        if (!val) return
        try {
          await add(this.subjectFrom)
          this.$message.success('添加学科成功')
        } catch (err) {
          this.$message.error('添加学科失败')
        }
        this.$refs.subjectFrom.resetFields()
        this.$emit('closed', this.subjectFrom)
        this.loadList()
      })
    },
    // 点击关闭按钮
    handleClose() {
      this.$emit('closed')
      this.$refs.subjectFrom.resetFields()
    }
  }
}
</script>

<style scoped lang="less"></style>
